<template>
  <div class="container">
    <div class="add-henji">
      <div class="add-henji-title">有什么要分享给大家的:</div>
      <textarea rows="3" class="form-control" placeholder="书写你的痕迹..." v-model="henjiContent"></textarea>
      <button class="btn btn-success btn-add" @click="addHenji">发布</button>
    </div>
    <div class="self-henji">
      我的痕迹:
      <div class="piece-henji" v-for="(piece, index) in henjis" v-bind:key="piece.id">
        <div class="username">
          {{ userinfo.username }}
        </div>
        <div class="time">
          {{ piece.writedate }}
        </div>
        <div class="content">
          {{ piece.content }}
        </div>
        <div class="delect">
          <a href="javascript:void(0);" @click="deleteHenji(index, piece.id)">删除</a>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  name: 'selfLife',
  mounted () {
    this.$http.post('/java_kunpeng/getHenji')
      .then((response) => {
        const json = response.data
        if (json.state === '0') {
          this.henjis = json.henjis
        } else {
          alert('获取失败！' + json.msg)
        }
      })
      .catch((error) => {
        alert(error.toString())
      })
  },
  data () {
    return {
      henjiContent: '',
      henjis: []
    }
  },
  computed: {
    ...mapGetters([
      'userinfo'
    ])
  },
  methods: {
    addHenji: function () {
      this.$http.post('/java_kunpeng/addHenji', {
        henjiContent: this.henjiContent
      })
        .then((response) => {
          const json = response.data
          if (json.state === '0') {
            const newHenji = {
              id: json.info.id,
              content: this.henjiContent,
              writedate: json.info.writedate
            }
            this.henjis.unshift(newHenji)
            this.henjiContent = ''
          } else {
            alert('添加失败！' + json.msg)
          }
        })
        .catch((error) => {
          alert(error.toString())
        })
    },
    deleteHenji: function (index, id) {
      this.$http.post('/java_kunpeng/delHenji', {
        henjiid: id
      })
        .then((response) => {
          const json = response.data
          if (json.state === '0') {
            this.henjis.splice(index, 1)
          } else {
            alert('删除失败！' + json.msg)
          }
        })
        .catch((error) => {
          alert(error.toString())
        })
    }
  }
}
</script>

<style scoped>
  .add-henji-title {
    margin-bottom: 10px;
  }
  .add-henji {
    width: 70%;
    margin: 20px auto 20px;
  }
  .self-henji {
    width: 70%;
    margin: auto;
  }
  .piece-henji {
    border: 2px gainsboro solid;
    border-radius: 5px;
    padding: 15px;
  }
  .username {
    display: inline;
    font-size: 18px;
    line-height: 25px;
  }
</style>
